<template>
  <div class="sync-log-table">
    <div class="table-header">
      <a-space>
        <a-select
          v-model:value="filters.status"
          placeholder="执行状态"
          style="width: 150px"
          allowClear
          @change="handleFilterChange"
        >
          <a-select-option value="running">运行中</a-select-option>
          <a-select-option value="success">成功</a-select-option>
          <a-select-option value="failed">失败</a-select-option>
        </a-select>
        <a-range-picker
          v-model:value="filters.dateRange"
          placeholder="执行时间"
          style="width: 250px"
          @change="handleFilterChange"
        />
        <a-button type="primary" @click="loadSyncLogs">
          <template #icon><SearchOutlined /></template>
          查询
        </a-button>
      </a-space>
    </div>

    <a-table
      :columns="tableColumns"
      :data-source="syncLogs"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handlePaginationChange"
      :scroll="{ x: 1200 }"
      :row-class-name="getRowClassName"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <a-badge
            :status="getExecutionStatusBadge(record.status)"
            :text="getExecutionStatusText(record.status)"
          />
        </template>
        <template v-if="column.key === 'duration'">
          <div class="duration-info">
            <div>{{ formatDuration(record.duration) }}</div>
            <div class="performance-info" v-if="record.performance_metrics">
              <a-tag color="blue" size="small">
                速度: {{ formatSpeed(record.performance_metrics.records_per_second) }}
              </a-tag>
            </div>
          </div>
        </template>
        <template v-if="column.key === 'start_time'">
          <div>
            <div>{{ formatDateTime(record.start_time) }}</div>
            <div class="end-time" v-if="record.end_time">
              结束: {{ formatDateTime(record.end_time) }}
            </div>
          </div>
        </template>
        <template v-if="column.key === 'records_info'">
          <div class="records-info">
            <div class="success-records">
              <CheckCircleOutlined style="color: #52c41a; margin-right: 4px;" />
              成功: {{ record.success_records }}
            </div>
            <div class="failed-records" v-if="record.failed_records > 0">
              <CloseCircleOutlined style="color: #ff4d4f; margin-right: 4px;" />
              失败: {{ record.failed_records }}
            </div>
            <div class="total-records">
              总计: {{ record.success_records + record.failed_records }}
            </div>
          </div>
        </template>
        <template v-if="column.key === 'actions'">
          <a-space>
            <a-button size="small" @click="handleViewLogDetail(record)">
              详情
            </a-button>
            <a-button
              size="small"
              type="primary"
              ghost
              v-if="record.status === 'failed'"
              @click="handleRetryExecution(record)"
            >
              重试
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { SearchOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue'
import { useSyncUtils } from '@/composables/useSyncData'

const props = defineProps({
  syncLogs: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  pagination: {
    type: Object,
    required: true
  },
  filters: {
    type: Object,
    required: true
  }
})

const emit = defineEmits([
  'load-sync-logs',
  'view-log-detail',
  'retry-execution',
  'pagination-change',
  'filter-change'
])

const { formatDateTime, formatDuration } = useSyncUtils()

// 获取执行状态徽章
const getExecutionStatusBadge = (status) => {
  const statusMap = {
    running: 'processing',
    success: 'success',
    failed: 'error'
  }
  return statusMap[status] || 'default'
}

// 获取执行状态文本
const getExecutionStatusText = (status) => {
  const statusMap = {
    running: '运行中',
    success: '成功',
    failed: '失败'
  }
  return statusMap[status] || status
}

// 格式化处理速度
const formatSpeed = (recordsPerSecond) => {
  if (!recordsPerSecond) return '0 条/秒'
  if (recordsPerSecond >= 1000) {
    return `${(recordsPerSecond / 1000).toFixed(1)}K 条/秒`
  }
  return `${Math.round(recordsPerSecond)} 条/秒`
}

// 优化的表格列配置
const tableColumns = computed(() => [
  {
    title: '执行ID',
    dataIndex: 'execution_id',
    key: 'execution_id',
    width: 180,
    fixed: 'left',
    ellipsis: true
  },
  {
    title: '任务名称',
    dataIndex: ['sync_task', 'task_name'],
    key: 'task_name',
    width: 150,
    ellipsis: true
  },
  {
    title: '执行状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    filters: [
      { text: '运行中', value: 'running' },
      { text: '成功', value: 'success' },
      { text: '失败', value: 'failed' }
    ]
  },
  {
    title: '开始时间',
    dataIndex: 'start_time',
    key: 'start_time',
    width: 160,
    sorter: true
  },
  {
    title: '执行时长',
    dataIndex: 'duration',
    key: 'duration',
    width: 120,
    sorter: true
  },
  {
    title: '记录统计',
    key: 'records_info',
    width: 150
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    fixed: 'right'
  }
])

// 获取行类名，用于状态视觉区分
const getRowClassName = (record) => {
  if (record.status === 'running') return 'table-row-running'
  if (record.status === 'failed') return 'table-row-failed'
  if (record.status === 'success') return 'table-row-success'
  return ''
}

// 事件处理函数
const loadSyncLogs = () => emit('load-sync-logs')

const handleViewLogDetail = (log) => emit('view-log-detail', log)

const handleRetryExecution = (log) => emit('retry-execution', log)

const handlePaginationChange = (pagination, filters, sorter) => {
  emit('pagination-change', pagination)
}

const handleFilterChange = () => emit('filter-change')
</script>

<style scoped>
.sync-log-table {
  background: white;
  border-radius: 8px;
  padding: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.duration-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.performance-info {
  display: flex;
  align-items: center;
}

.records-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  font-size: 12px;
}

.success-records,
.failed-records,
.total-records {
  display: flex;
  align-items: center;
}

.success-records {
  color: #52c41a;
}

.failed-records {
  color: #ff4d4f;
}

.total-records {
  color: #666;
  font-weight: 500;
}

.end-time {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

:deep(.ant-table-tbody > tr.ant-table-row:hover > td) {
  background: #f5f5f5;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

:deep(.table-row-running > td) {
  background-color: #e6f7ff;
  animation: pulse 2s infinite;
}

:deep(.table-row-failed > td) {
  background-color: #fff2f0;
}

:deep(.table-row-success > td) {
  background-color: #f6ffed;
}

@keyframes pulse {
  0% {
    background-color: #e6f7ff;
  }
  50% {
    background-color: #bae7ff;
  }
  100% {
    background-color: #e6f7ff;
  }
}

:deep(.ant-btn-sm) {
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .table-header {
    flex-direction: column;
    align-items: stretch;
  }

  .table-header .ant-space {
    width: 100%;
    flex-wrap: wrap;
  }

  .records-info {
    font-size: 11px;
  }
}
</style>